
/*
 *  routes index
 *  auth guoqing.ma
 */
var User = require('../model/user.js');
var Topic = require('../model/topic.js')
var markdown = require('markdown').markdown;

exports.index = function(req, res){
	Topic.getTopics('',function(err,topics){
		console.log(topics);
		res.render('index', { title: 'Express' , topics:topics});
	});
};

exports.login = function(req,res){
	res.render('login',{ title: 'login' });
};

exports.logout = function(req,res){
	req.session.user = null;
	req.flash('success','退出成功');
	res.redirect('/');
}

exports.register = function(req,res){
	res.render('register');
};
// login  system
exports.log =  function(req,res){
	var newUser = new User({
		name:req.body.name,
		password:req.body.password
	});
	User.login(newUser,function(err,user){
		console.log(user);
		if(err){
			console.log('err');
			req.flash('err',err);
			return res.redirect('/login');
		}
		if(user){
			console.log('user');
			console.log(user);
			req.session.user = user;
			res.redirect('/');
		}else{
			console.log('havent  user');
			req.flash('err','账户名或密码错误');
			console.log(req);
			res.redirect('/login');
		}
	});
}
exports.reg = function(req,res){
	console.log(User);
	console.log(req.body);
	if(req.body['password'] != req.body['repassword']){
		req.flash('err','两次输入的密码不一致');
		return res.redirect('/register');
	};
	var newUser = new User({
		name:req.body.name,
		password:req.body.password,
	});
	User.getUser(newUser,function(err,user){
		if(user){
			err = '用户名已存在';
		}
		if(err){
			req.flash('err',err);
			return res.redirect('/register');
		}
		newUser.save(function(err,user){
			if(err){
				console.log(err);
				console.log(user);
			}
			req.session.user = newUser;
			req.flash('success','注册成功');
			res.redirect('/');
		});
	});
};
//  添加话题
exports.topCreate = function(req,res){
	res.render("create");
};

exports.create = function(req,res){
	if(req.body['title'] != null && req.body['content'] != null){
		var user = req.session.user;
		var topic = new Topic({
			title:req.body.title,
			content:markdown.toHTML(req.body.content),
			userId:user._id,
			userName:user.name
		});
		Topic.save(topic,function(err,topic){
			req.flash('success',"话题发布成功");
			res.redirect('/');
		});	
	}
};
exports.topic = function(req,res){
	console.log(req.params.topicId);
	Topic.getTopicById(req.params.topicId,function(err,topic){
		if(err){
			res.render('index');
		}
		res.render('topic',{topic:topic});
	});
	
};

